package com.fengwk.support.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.FileChannel;

import com.fengwk.support.exception.BaseException;
import com.fengwk.support.util.LoggerUtils.Logger;

public class NioUtils {
	
	private static final Logger LOG = LoggerUtils.getLogger(NioUtils.class);
	
	private static final int R = 1;// 输入
	private static final int W = 2;// 输出
	private static final int RW = 3;// 输出
	
	private static final String DEFAULT_RANDOM_ACCESS_FILE = "rw";
	
	private NioUtils() {
		throw new BaseException("can not instance " + getClass());
	}
	
	public static void copy(String inFilePath, String outFilePath) throws IOException {
		FileChannel inChannel = getFileChannel(inFilePath, R);
		FileChannel outChannel = getFileChannel(outFilePath, W);
		ByteBuffer byteBuffer = getByteBuffer(1024);
		while(inChannel.read(byteBuffer) != -1) {
			byteBuffer.flip();
			outChannel.write(byteBuffer);
			byteBuffer.clear();
		}
		close(outChannel);
		close(inChannel);
	}
	
	// 获取channel通道
	@SuppressWarnings("resource")
	private static FileChannel getFileChannel(String filePath, int direction) {
		try {
			if(direction == R) {
				return new FileInputStream(filePath).getChannel();
			}else if (direction == W) {
				return new FileOutputStream(filePath).getChannel();
			} else if (direction == RW) {
				return new RandomAccessFile(filePath, DEFAULT_RANDOM_ACCESS_FILE).getChannel();
			}
		} catch (FileNotFoundException e) {
		    LOG.error(e);
		}
		return null;
	}
	
	// 获取ByteBuffer
	private static ByteBuffer getByteBuffer(int capacity) {
		return ByteBuffer.allocate(capacity);
	}
	
	private static void close(Channel channel) {
		if(channel != null && channel.isOpen()) {
			try {
				channel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
}
